package com.ezops.poc.processor;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ezops.model.DefaultFieldValidationError;
import com.ezops.poc.bo.DynamicModel;
import com.ezops.poc.bo.OTResponseFields;
import com.ezops.poc.bo.TradeStatus;
import com.ezops.poc.dao.ClientModelDAO;
import com.ezops.poc.validations.EzopsValidationException;
import com.ezops.poc.validations.TradeIndentifier;

@Component("OTResponseHandler")
public class OTResponseHandler implements Processor {

	private static final Logger logger = LoggerFactory
			.getLogger(OTResponseHandler.class);

	@Autowired
	private ClientModelDAO clientDAO;

	@Override
	public void process(Exchange exchange) throws Exception {
		final DynamicModel model = exchange.getIn().getBody(DynamicModel.class);
		logger.debug(
				"Processing OT Response with ezops id [{}] with status {}",
				model.getField(OTResponseFields.EZOPS_ID.getName()),
				model.getField(OTResponseFields.STATUS.getName()));

		if ("Passed".equalsIgnoreCase(model.getField(OTResponseFields.STATUS
				.getName()))) {
			// update clientModel
			clientDAO.update(Integer.parseInt(trimQuotes(model
					.getField(OTResponseFields.EZOPS_ID.getName()))),
					TradeStatus.PROCESSED, Integer.parseInt(trimQuotes(model
							.getField(OTResponseFields.OT_ID.getName()))));

		} else {
			// throw validation exception and the exception handler will insert
			// the exception record and also update the status
			EzopsValidationException exception = new EzopsValidationException(
					getIdentifier(model));

			exception
					.addValidationError(new DefaultFieldValidationError(
							trimQuotes(model.getField(OTResponseFields.ERROR
									.getName())), null,null)); // throw exceotion
			throw exception;
		}

	}

	private TradeIndentifier getIdentifier(DynamicModel model) {
		return clientDAO.getTradeIdentifier(Integer.parseInt(trimQuotes((model
				.getField(OTResponseFields.EZOPS_ID.getName())))));
	}

	private String trimQuotes(String value) {
		return value.replaceAll("\"", "");
	}
}
